﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Skybot.Docs
{
    /// <summary>
    /// 扩展方法 
    /// </summary>
    public static class WordExtendMethod
    {

        /// <summary>
        /// 产生替换的随机数
        /// </summary>
        private static Random random = new Random(DateTime.Now.Millisecond);
        /// <summary>
        /// 用近意词替换
        /// </summary>
        /// <param name="str">需要替换的字符串</param>
        /// <param name="isTag">是不是将替换的部分标出来</param>
        /// <remarks>数据算法说明
        /// 1.先对需要替换的数据进行&amp;#;编码
        /// 2.循环对每次的汉字进行替换
        /// </remarks>
        /// <returns>返回替换后的字符串替换部分为&amp;#编码</returns>
        public static string ReplaceByNearSynonym(this  string str,bool isTag=false)
        {

            foreach (WordEntity entity in WordUnitys.Instance.Caches)
            {
                //替换数据
                if (entity.NearSynonym.Length > 0)
                {
                    string[] ttarr = entity.NearSynonymUnicode.Split('|');
                    int index = random.Next(0, ttarr.Length - 1);
                    //替换为的字符串
                    string replace = ttarr[index];
                    //包含
                    if (replace.Length > 0 && !replace.Contains("*"))
                    {
                        if (!isTag)
                        {
                            //改进性能的算法
                            str = str.Replace(entity.OriginWord, replace);
                        }
                        else {
                            str = str.Replace(entity.OriginWord, string.Format("{0}{1}{2}", "<span style='color:#ff0000;'>",replace,"</span>"));
                        }
                    }
                    
                    //string[] ttarr = entity.NearSynonym.Split('|');
                    ////以前的算法需要即时拼接字符串
                    //str = str.Replace(entity.OriginWord,
                    //  string.Join("", (from p in replace.ToArray()
                    //                   select "&#" + (int)p + ";").ToArray())
                    //    );
                    //清空变量引用
                    ttarr = null;
                    replace = null;
                }
            }


            return str;
        }
    }
}